package com.lxk.service.event.handler;

import com.lxk.common.EventTypeEnum;
import com.lxk.common.GsonUtils;
import com.lxk.dao.BlogDbDao;
import com.lxk.dao.CommentDao;
import com.lxk.domain.BlogDbEntity;
import com.lxk.domain.CommentDbEntity;
import com.lxk.domain.dto.CommentDto;
import com.lxk.service.event.AbstractEventHandler;
import com.lxk.service.event.domain.EventDto;
import com.lxk.service.utils.EmailSendService;
import com.lxk.service.utils.SensitiveWordsHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Lxk on 2020/7/25.
 */
@Component
public class CommentPubHandler extends AbstractEventHandler<EventDto> {

    private static final Logger logger = LoggerFactory.getLogger(CommentPubHandler.class);

    @Value("${email.author}")
    private String authorEmail;

    @Value("${email.account}")
    private String emailAccount;

    @Resource
    private CommentDao commentDao;

    @Resource
    private BlogDbDao blogDbDao;

    @Resource
    private EmailSendService emailSendService;

    @Resource
    private SensitiveWordsHandler sensitiveWordsHandler;

    @Override
    public List<EventTypeEnum> supports() {
        return Arrays.asList(EventTypeEnum.EVENT_COMMENT_PUBLISH);
    }

    @Override
    public boolean handleEvent(EventDto eventDto) {
        logger.info("Comment eventDto:{}",eventDto);
        CommentDto replyComment = GsonUtils.getGson().fromJson(eventDto.getContent(),CommentDto.class);
        String filterContent = sensitiveWordsHandler.filter(replyComment.getComment());
        String now = emailDateTime();
        String fromEmail = null,toEmail = null;
        String emailTitle = null;
        StringBuffer emailContentSb = new StringBuffer();
        BlogDbEntity blogDbEntity = blogDbDao.queryById(Long.parseLong(replyComment.getBlogId()));
        if(!StringUtils.isEmpty(replyComment.getToname())){
            //回复评论
            CommentDbEntity srcComment = commentDao.queryById(Long.parseLong(replyComment.getCommentId()));
            emailTitle = "来自望岳笔记的评论回复";
            fromEmail = emailAccount;
            toEmail = srcComment.getEmail();
            emailContentSb.append("<p>尊敬的").append(srcComment.getNickName()).append("女士or先生:</p>")
                    .append("<p>&emsp;&emsp;你好!</p>")
                    .append("<p>&emsp;&emsp;你在博客").append("<a href='http://www.iamlxk.cn/blog/detail?id=")
                    .append(replyComment.getBlogId()).append("#comment-container' >").append(blogDbEntity.getTitle())
                    .append("</a>").append("中的评论'").append(sensitiveWordsHandler.filter(srcComment.getContent())).append("'收到了来自").append(replyComment.getNickname())
                    .append("的回复，期待您的查看和回复，祝您学习or工作顺利！</p>")
                    .append("<p>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;")
                    .append("&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;from 望岳笔记工具人</p>")
                    .append("<p>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;")
                    .append("&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;")
                    .append(now).append("</p>").append("&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;<h3>≧◔◡◔≦</h3>");
        }else{
            //回复博客(博客首评)
            fromEmail = emailAccount;
            toEmail = authorEmail;
            emailTitle = "您的博客望岳笔记有新的评论";
            emailContentSb.append("<p>尊敬的作者:</p>")
                    .append("<p>&emsp;&emsp;您好!</p>")
                    .append("<p>&emsp;&emsp;您的博客<a href='http://www.iamlxk.cn/blog/detail?id=").append(blogDbEntity.getId())
                    .append("#comment-container' >").append(blogDbEntity.getTitle()).append("</a>收到了来自").append(replyComment.getNickname())
                    .append("的评论，内容为：").append(sensitiveWordsHandler.filter(replyComment.getComment())).append(",祝您一切顺利，再接再厉，创作出更高质量的文章</p>")
                    .append("<p>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;from 望岳博客</p>")
                    .append("<p>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;")
                    .append(now).append("</p>").append("&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;<h3>≧◔◡◔≦</h3>");
        }
        try{
            emailSendService.sendEmail(fromEmail,toEmail,emailTitle,emailContentSb.toString());
            return true;
        }catch (Exception e){
            logger.error("邮件通知失败... eventDto:{},e:",eventDto,e);
        }
        return false;
    }

    private String emailDateTime(){
        LocalDateTime now = LocalDateTime.now();
        String curTime = now.toString().split("\\.")[0];
        curTime = curTime.replace("T"," ");
        return curTime;
    }

    @Override
    public boolean isFailedRetry() {
        return true;
    }

    @Override
    public Class<EventDto> eventType() {
        return EventDto.class;
    }


}
